<template>
	<view class="add-form-wrap">
		<uni-forms ref="formRef" :modelValue="formData" :rules="eventRules">
			<uni-forms-item label="事务名称" name="eventName">
				<uni-easyinput maxlength="10" v-model="formData.eventName" placeholder="请输入事务名称" />
			</uni-forms-item>
			<uni-forms-item label="金额" name="amount">
				<uni-easyinput type="number" v-model="formData.amount" placeholder="请输入金额" />
			</uni-forms-item>
			<uni-forms-item label="变动类型" name="changeType">
				<uni-data-checkbox mode="button" v-model="formData.changeType" :localdata="changeTypeList" />
			</uni-forms-item>
			<button @click="submit">确认</button>
		</uni-forms>
	</view>
</template>

<script lang="ts" setup>
	import { eventRules, changeTypeList } from '../utils/contant'
	import { reactive, ref, watch } from 'vue';
	import type { DB } from '../indexDB/DBType';
	const formRef = ref(null);
	const props = defineProps<{
		eventName ?: string;
		amount ?: number;
		changeType ?: 'expend' | 'income'
	}>()
	const emit = defineEmits<{
		(e : 'submit', data : DB.EventRecord) : void;
	}>()
	const formData = reactive<DB.EventRecord>({
		eventName: '',
		amount: 0,
		changeType: 'expend'
	})
	watch(props, (data) => {
		const { eventName, amount, changeType } = data;
		eventName && (formData.eventName = eventName);
		amount && (formData.amount = amount);
		changeType && (formData.changeType = changeType);
	})
	const submit = () => {
		formRef.value.validate().then((res : Omit<DB.EventRecord, 'amount'> & { amount : string }) => {
			emit('submit', {
				...res,
				amount: Number(res.amount)
			});
		}).catch(() => null);
	}
</script>

<style lang="scss" scoped>
	.add-form-wrap {
		padding: 15px;
	}
</style>